package com.cyt.work.site.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.work.site.dao.StudentDao;
import com.cyt.work.site.model.po.Student;
import com.cyt.work.site.model.vo.StudentVo;
import com.cyt.work.site.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 微官网-新生报名Service层实现类
 *
 * @author rong yuan
 * @date 2019-7-8 19:39:31
 */
@Service("studentService")
public class StudentServiceImpl extends BaseServiceImpl<Student> implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Autowired
    public void setBaseDao(StudentDao studentDao) {
        this.baseDao = studentDao;
    }

    /**
     * 查询对象集合
     *
     * @param studentVo 对象
     * @return List 对象集合
     * @author rong yuan
     * @date 2019-7-8 19:39:31
     */
    @Override
    public List<Student> listExample(StudentVo studentVo) {
        Example example = new Example(Student.class);
        example.setOrderByClause(" create_time desc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("removeTag", BaseConstant.REMOVE_TAG_NO);
        if (StrUtil.isNotEmpty(studentVo.getApplyId())) {
            criteria.andEqualTo("applyId", studentVo.getApplyId());
        }
        if (StrUtil.isNotEmpty(studentVo.getPeriodType())) {
            criteria.andEqualTo("periodType", studentVo.getPeriodType());
        }
        if (StrUtil.isNotEmpty(studentVo.getLoginName())) {
            criteria.andLike("loginName", "%" + studentVo.getLoginName() + "%");
        }
        if (StrUtil.isNotEmpty(studentVo.getStudentCode())) {
            criteria.andLike("studentCode", "%" + studentVo.getStudentCode() + "%");
        }
        if (StrUtil.isNotEmpty(studentVo.getStudentName())) {
            criteria.andLike("studentName", "%" + studentVo.getStudentName() + "%");
        }
        if (StrUtil.isNotEmpty(studentVo.getIdNumber())) {
            criteria.andLike("idNumber", "%" + studentVo.getIdNumber() + "%");
        }
        if (StrUtil.isNotEmpty(studentVo.getGuardianIdNumber())) {
            criteria.andLike("guardianIdNumber", "%" + studentVo.getGuardianIdNumber() + "%");
        }
        return studentDao.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param studentVo 接受参数对象
     * @param pageNum   分页数
     * @param pageSize  每页显示条数
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-8 19:39:31
     */
    @Override
    public ReturnResult page(StudentVo studentVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<Student> list = listExample(studentVo);
        PageInfo<Student> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param studentVo 参数接受对象
     * @param sysUser   当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-8 19:39:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(StudentVo studentVo, SysUser sysUser) {
        ReturnResult returnResult = checkStudentInfo(studentVo);
        if (returnResult.getCode() != 0) {
            return returnResult;
        }
        if (StrUtil.isEmpty(studentVo.getId())) {
            Student student;
            if (sysUser == null) {
                student = new Student();
                student.setId(BaseUtil.uId());
                student.setRemoveTag(DictCode.BASE_REMOVE_TAG_NORMAL);
                student.setCreateTime(new Date());
                student.setUpdateTime(new Date());
            } else {
                student = new Student(sysUser);
            }
            student.setApplyId(studentVo.getApplyId());
            student.setPeriodType(studentVo.getPeriodType());
            student.setLoginName(studentVo.getLoginName());
            student.setPassword(studentVo.getPassword());
            student.setStudentCode(studentVo.getStudentCode());
            student.setStudentName(studentVo.getStudentName());
            student.setIdNumber(studentVo.getIdNumber());
            student.setGuardianIdNumber(studentVo.getGuardianIdNumber());
            int num = studentDao.insert(student);
            if (num > 0) {
                return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
            } else {
                return new ReturnResult(ErrorCode.CODE_1, BaseConstant.DATABASE_ERROR_INSERT);
            }
        } else {
            Student student = studentDao.selectByPrimaryKey(studentVo.getId());
            student.setApplyId(studentVo.getApplyId());
            student.setPeriodType(studentVo.getPeriodType());
            student.setLoginName(studentVo.getLoginName());
            student.setPassword(studentVo.getPassword());
            student.setStudentCode(studentVo.getStudentCode());
            student.setStudentName(studentVo.getStudentName());
            student.setIdNumber(studentVo.getIdNumber());
            student.setGuardianIdNumber(studentVo.getGuardianIdNumber());
            student.setUpdateTime(new Date());
            student.setUpdateUser(sysUser.getId());
            int num = studentDao.updateByPrimaryKey(student);
            if (num > 0) {
                return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
            } else {
                return new ReturnResult(ErrorCode.CODE_1, BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
    }

    private ReturnResult checkStudentInfo(StudentVo studentVo) {
        StudentVo vo;
        List<Student> studentList;
        //校验帐号
        vo = new StudentVo();
        vo.setLoginName(studentVo.getLoginName());
        studentList = listExample(vo);
        if (studentList != null && studentList.size() > 0) {
            if (!studentList.get(0).getId().equals(studentVo.getId())) {
                return new ReturnResult(ErrorCode.CODE_1, "该帐号已注册！");
            }
        }
        //校验学籍号
        vo = new StudentVo();
        vo.setStudentCode(studentVo.getStudentCode());
        studentList = listExample(vo);
        if (studentList != null && studentList.size() > 0) {
            if (!studentList.get(0).getId().equals(studentVo.getId())) {
                return new ReturnResult(ErrorCode.CODE_1, "该学籍号已注册！");
            }
        }
        //校验身份证号
        vo = new StudentVo();
        vo.setIdNumber(studentVo.getIdNumber());
        studentList = listExample(vo);
        if (studentList != null && studentList.size() > 0) {
            if (!studentList.get(0).getId().equals(studentVo.getId())) {
                return new ReturnResult(ErrorCode.CODE_1, "该身份证号已注册！");
            }
        }
        return new ReturnResult();
    }

    /**
     * 根据条件逻辑删除
     *
     * @param studentVo 参数接受对象
     * @param sysUser   当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-8 19:39:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(StudentVo studentVo, SysUser sysUser) {
        //要修改的字段
        Student student = new Student();
        student.setRemoveTag(BaseConstant.REMOVE_TAG_YES);
        student.setUpdateUser(sysUser.getId());
        student.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(studentVo.getId())) {
            criteria.andIn("id", Arrays.asList(studentVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", BaseConstant.REMOVE_TAG_NO);
        studentDao.updateByExampleSelective(student, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param studentVo 参数接受对象
     * @param sysUser   当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-8 19:39:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(StudentVo studentVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(studentVo.getId())) {
            criteria.andIn("id", Arrays.asList(studentVo.getId().split(",")));
        }
        studentDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 数据导出
     *
     * @param response  响应对象
     * @param studentVo 接受参数对象
     * @author rong yuan
     * @date 2019/7/11 15:55
     */
    @Override
    public void exportStudent(HttpServletResponse response, StudentVo studentVo) {
        List<Student> list = listExample(studentVo);
        EasyPoiUtil.exportExcel(list, "新生报名信息", "新生报名信息", Student.class, "新生报名信息.xls", response);
    }
}